package com.zhongxin.wymovieticketfragment;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.zhongxin.wymovieticket.CinemaDetaileActivity;
import com.zhongxin.wymovieticket.GaoDeMapActivity;
import com.zhongxin.wymovieticket.R;
import com.zhongxin.wymovieticket.SearChActivity;
import com.zhoujing.Entity.Cinema;
import com.zhoujing.Entity.CinemaDetailEntity;
import com.zhoujing.Entity.CountryCity;
import com.zhoujing.adapter.HeadViewpagerAdapter;
import com.zhoujing.adapter.MeAdapter;
import com.zhoujing.utils.JsonUtils;
import com.zhoujing.utils.JsonUtils.JsonObjectCallBack;
import se.emilsjolander.stickylistheaders.StickyListHeadersListView;

public class CinemaFragment extends Fragment implements OnPageChangeListener {

	// viewpager下面的小圆点数
	private ImageView[] imageViews = null;
	private ImageView imageView = null;
	private AtomicInteger what = new AtomicInteger(0);
	private final static String DISTRIC = "http://piao.163.com/m/cinema/list.html?dest_city=440300&longitude=&latitude=&city=440300&apiVer=14&mobileType=android&deviceId=08:00:27:f4:e2:00&channel=netease&ver=4.8";
	// 默认设置为true
	private boolean isContinue = true;
	private List<Cinema> list = new ArrayList<Cinema>();
	private TextView baiduTextView;

	private RequestQueue queue;
	private final Handler viewHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			viewPager.setCurrentItem(msg.what, false);
		};
	};
	private ViewPager viewPager;
	private RelativeLayout aD;
	private CountryCity countryCity;
	private StickyListHeadersListView listView;

	public CinemaFragment() {
		// TODO Auto-generated constructor stub
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		queue = Volley.newRequestQueue(getActivity());

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub

		// 得到区域列表
		Bundle bundle = getArguments();
		countryCity = (CountryCity) bundle.getSerializable("countryCity");
		// initData();
		View view = inflater
				.inflate(R.layout.fragment_cinema, container, false);
		initView(view, inflater);
		GetData();

		
		return view;
	}

	// 下载网络数据
	private void GetData() {
		// TODO Auto-generated method stub
		JsonUtils.parseJsonObject(getActivity(), DISTRIC,
				new JsonObjectCallBack() {

					private CinemaDetailEntity cinemaDetailEntity;

					@Override
					public void jsonObjectCallBack(JSONObject jsonObject) {
						// TODO Auto-generated method stub
						try {
							cinemaDetailEntity = new CinemaDetailEntity();
							int retcode = jsonObject.getInt("retcode");
							String retdesc = jsonObject.getString("retdesc");

							List<Cinema> cinemas = new ArrayList<Cinema>();
							JSONArray cinemaList = jsonObject
									.getJSONArray("cinemaList");
							for (int i = 0; i < cinemaList.length(); i++) {
								Cinema cinema = new Cinema();
								cinema.setId(cinemaList.getJSONObject(i)
										.getInt("id"));
								cinema.setName(cinemaList.getJSONObject(i)
										.getString("name"));
								cinema.setDistrictId(cinemaList
										.getJSONObject(i).getString(
												"districtId"));
								cinema.setAddress(cinemaList.getJSONObject(i)
										.getString("address"));
								cinema.setTel(cinemaList.getJSONObject(i)
										.getString("tel"));
								cinema.setIsSeatSupport(cinemaList
										.getJSONObject(i).getInt(
												"isSeatSupport"));
								cinema.setIsCouponSupport(cinemaList
										.getJSONObject(i).getInt(
												"isCouponSupport"));
								cinema.setIsGroupBuySupport(cinemaList
										.getJSONObject(i).getInt(
												"isGroupBuySupport"));
								cinema.setIsImaxSupport(cinemaList
										.getJSONObject(i).getInt(
												"isImaxSupport"));
								cinema.setMsg(cinemaList.getJSONObject(i)
										.getString("msg"));
								cinema.setCircleName(cinemaList
										.getJSONObject(i).getString(
												"circleName"));
								cinema.setCoord(cinemaList.getJSONObject(i)
										.getString("coord"));
								cinema.setGrade(cinemaList.getJSONObject(i)
										.getString("grade"));
								cinema.setSubwayLine(cinemaList
										.getJSONObject(i).getString(
												"subwayLine"));
								cinema.setNewCoupon(cinemaList.getJSONObject(i)
										.getString("newCoupon"));
								cinema.setBusline(cinemaList.getJSONObject(i)
										.getString("busline"));
								cinema.setNotice(cinemaList.getJSONObject(i)
										.getString("notice"));
								cinema.setNoScheduleMsg(cinemaList
										.getJSONObject(i).getString(
												"noScheduleMsg"));
								cinema.setIsSeatOccupy(cinemaList
										.getJSONObject(i)
										.getInt("isSeatOccupy"));
								cinema.setDistance(cinemaList.getJSONObject(i)
										.getString("distance"));
								cinema.setLowPrice(cinemaList.getJSONObject(i)
										.getString("lowPrice"));
								cinema.setScreenings(cinemaList
										.getJSONObject(i).getString(
												"screenings"));
								cinema.setIsDiscount(cinemaList
										.getJSONObject(i).getInt("isDiscount"));
								cinema.setSpell(cinemaList.getJSONObject(i)
										.getString("spell"));
								cinema.setIsAvailableCoupon(cinemaList
										.getJSONObject(i).getString(
												"isAvailableCoupon"));
								cinema.setCouponLimitDesc(cinemaList
										.getJSONObject(i).getString(
												"isAvailableCoupon"));
								cinemas.add(cinema);
							}
							cinemaDetailEntity.setRetcode(retcode);
							cinemaDetailEntity.setRetdesc(retdesc);
							cinemaDetailEntity.setCinemas(cinemas);
							if (list != null && list.size() > 0) {
								list.clear();
							}
							if (cinemaDetailEntity.getCinemas() != null
									&& cinemaDetailEntity.getCinemas().size() > 0) {

								for (int i = 0; i < countryCity
										.getDistrictList().size(); i++) {
									for (int j = 0; j < cinemaDetailEntity
											.getCinemas().size(); j++) {
										if (countryCity
												.getDistrictList()
												.get(i)
												.getId()
												.equals(cinemaDetailEntity
														.getCinemas().get(j)
														.getDistrictId())) {
											list.add(cinemaDetailEntity
													.getCinemas().get(j));
										}
									}
									
									
								}
                                if (list!=null&&list.size()>0) {
                                	MeAdapter adapter = new MeAdapter(
    										getActivity(), list, countryCity 
    												.getDistrictList());
    								listView.setAdapter(adapter);
    								listView.setDrawingListUnderStickyHeader(true);
    								listView.setAreHeadersSticky(true);
    								/**
    								 * 点击跳转
    								 */
    								listView.setOnItemClickListener(new OnItemClickListener() {

										@Override
										public void onItemClick(
												AdapterView<?> arg0, View arg1,
												int arg2, long arg3) {
											// TODO Auto-generated method stub
											Toast.makeText(getActivity(), "----点击了--"+arg2, 1).show();
											if (list!=null&&list.size()>0) {
												
												Intent intent=new Intent(getActivity(),CinemaDetaileActivity.class);
												Bundle bundle=new Bundle();
												bundle.putSerializable("cinemaDetailEntity",list.get(arg2-1));
												intent.putExtra("bundle", bundle);
												startActivity(intent);
											}
											
										}
									});
								}
								
								// 点击百度按钮
								baiduTextView
										.setOnClickListener(new OnClickListener() {

											@Override
											public void onClick(View arg0) {
												// TODO Auto-generated method
												// stub
												Intent intent = new Intent(
														getActivity(),
														GaoDeMapActivity.class);
												Bundle bundle = new Bundle();
												bundle.putSerializable(
														"cinemaDetailEntity",
														cinemaDetailEntity);
												intent.putExtra("bundle",
														bundle);
												startActivity(intent);
											}
										});
							}

						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

					}
				}, queue);
	}

	private void initView(View view, LayoutInflater inflater) {
		baiduTextView = (TextView) view.findViewById(R.id.cinema_baidu_icon);
		listView = (StickyListHeadersListView) view
				.findViewById(R.id.fragment_cinema_listview);
		View headView = LayoutInflater.from(getActivity()).inflate(
				R.layout.fragment_cinema_header, null);
		// 初始化viewpager
		initViewPager(headView);

		// 点击了搜索
		TextView searchView = (TextView) headView
				.findViewById(R.id.cinea_seatrch_textview);
		searchView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(getActivity(), SearChActivity.class);
				startActivity(intent);
			}
		});
		// 点击关闭按钮
		aD = (RelativeLayout) headView.findViewById(R.id.cinema_ad);
		TextView btnClose = (TextView) headView.findViewById(R.id.text_close);
		btnClose.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				aD.setVisibility(View.GONE);
			}
		});
		// listview添加头部
		listView.addHeaderView(headView);

	}

	public void initViewPager(View headView) {
		viewPager = (ViewPager) headView
				.findViewById(R.id.fragment_cinema_viewpager);
		ViewGroup group = (ViewGroup) headView.findViewById(R.id.view_group);
		// 放广告的
		List<View> views = new ArrayList<View>();
		ImageView imageView1 = new ImageView(getActivity());
		imageView1.setBackgroundResource(R.drawable.ic_launcher);
		ImageView imageView2 = new ImageView(getActivity());
		imageView2.setBackgroundResource(R.drawable.activity_default);
		views.add(imageView1);
		views.add(imageView2);
		// 初始化小圆点的背景
		imageViews = new ImageView[views.size()];
		for (int i = 0; i < views.size(); i++) {
			imageView = new ImageView(getActivity());
			imageView.setLayoutParams(new LayoutParams(8, 8));
			imageView.setPadding(20, 20, 20, 20);
			imageViews[i] = imageView;
			if (i == 0) {
				imageViews[i]
						.setBackgroundResource(R.drawable.icon_sequence_selected);
			} else {
				imageViews[i]
						.setBackgroundResource(R.drawable.icon_sequence_unselected);
			}
			group.addView(imageViews[i]);
		}
		HeadViewpagerAdapter headViewpagerAdapter = new HeadViewpagerAdapter(
				views);
		viewPager.setAdapter(headViewpagerAdapter);
		// 判断当手指触碰viewpager是，是否自动播放
		viewPager.setOnPageChangeListener(this);
		viewPager.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View arg0, MotionEvent arg1) {
				// TODO Auto-generated method stub
				switch (arg1.getAction()) {
				case MotionEvent.ACTION_DOWN:
				case MotionEvent.ACTION_MOVE:
					isContinue = false;
					break;
				case MotionEvent.ACTION_UP:
					isContinue = true;
				default:
					isContinue = true;
					break;
				}
				return false;
			}
		});
		new Thread(new Runnable() {

			@Override
			public void run() {
				// 发消息
				while (true) {
					if (isContinue) {
						viewHandler.sendEmptyMessage(what.get());
						whatOption();
					}
				}
			}
		}).start();
	}

	private void whatOption() {
		what.incrementAndGet();
		if (what.get() > imageViews.length - 1) {
			what.getAndAdd(-2);

		}

		try {
			Thread.sleep(3000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void onPageScrollStateChanged(int arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onPageSelected(int arg0) {
		what.getAndSet(arg0);
		for (int i = 0; i < imageViews.length; i++) {
			imageViews[arg0]
					.setBackgroundResource(R.drawable.icon_sequence_selected);
			if (arg0 != i) {
				imageViews[i]
						.setBackgroundResource(R.drawable.icon_sequence_unselected);
			}
		}
	}
	

}
